package com.sgb.kjwl.viewmodel.manage;

import android.content.Context;
import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.blankj.utilcode.util.RegexUtils;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.UrlConfig;
import com.sgb.kjwl.api.service.WebsiteInfoAPI;
import com.sgb.kjwl.model.entity.manage.AliVideoBean;
import com.sgb.kjwl.model.entity.manage.CompanyTradesListEntity;
import com.sgb.kjwl.model.entity.manage.GloryHonorAdminEntity;
import com.sgb.kjwl.model.entity.manage.IPDetailEntity;
import com.sgb.kjwl.model.entity.manage.PromotionalAlbumEntity;
import com.sgb.kjwl.model.entity.manage.UpdataSpecialQualificationEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.ManageRepertory;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity2;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteUpDataJYDTActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteUpDataJingYingYeJiActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteUpDataRongYuRongYaoActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteUpDataZhiShiChanQuanActivity;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteUpDataZhuanXiangZiZhiActivity;
import com.sgb.member.entity.OperatingResultsEntity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.sgb.kjwl.api.service.WebsiteInfoAPI.WebsiteUrl.URL_ALL_SITE_ALBUM;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity.HANGYERONGYU;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity.QIYEDONGTAI;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity.QIYEXIANGCE;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity.QIYEXINXI;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity.QIYEZIZHI;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity.YEJIZHENGMING;
import static com.sgb.kjwl.view.ui.activity.manage.WebsiteReleaseActivity.ZHISHICHANQUAN;

/**
 * @author 张驰
 * @date 2021/5/10 15:37
 * @Description 企业网站发布列表
 * @name com.sgb.kjwl.viewmodel.manage
 */
public class WebsiteReleaseModule extends BaseViewModel {

    private WebsiteReleaseActivity activity;
    public ManageRepertory repertory;
    public int modeltype = 0; // 模块类型
    private int page = 1; //请求页数
    private int totalPage = 1; //总页数
    private String limit = "10"; //每页条数
    private String siteNo; // 网站编号
    private int siteType; // //网站类型  0-个人 1-企业 2-团队 默认为1
    private String typesOfPropertyRights; // 产权类型
    private String uploadType;//宣传展示 上传类型

    public void setUploadType(String uploadType) {
        this.uploadType = uploadType;
    }

    private MutableLiveData<List<Object>> listMutableLiveData = new MutableLiveData<>(new ArrayList<>());

    public WebsiteReleaseModule(WebsiteReleaseActivity websiteReleaseActivity, ManageRepertory repertory) {
        this.activity = websiteReleaseActivity;
        this.repertory = repertory;
    }

    public void setModeltype(int modeltype) {
        this.modeltype = modeltype;
    }

    public void setSiteNo(String siteNo) {
        this.siteNo = siteNo;
    }

    public void setSiteType(int siteType) {
        this.siteType = siteType;
    }

    public void setTypesOfPropertyRights(String typesOfPropertyRights) {
        this.typesOfPropertyRights = typesOfPropertyRights;
    }

    public MutableLiveData<List<Object>> getListMutableLiveData() {
        return listMutableLiveData;
    }

    /**
     * 更新数据
     */
    public void initData(boolean isLoadMore) {
        Map<String, String> map = new HashMap();
        page = isLoadMore ? page + 1 : 1;
        if (isLoadMore) { //当是加载更多的时候才拦截，否则不拦截
            if (totalPage < page) return;
        }
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        map.put("page", page + "");
        map.put("limit", limit + "");
        map.put("siteNo", siteNo);
        map.put("siteType", siteType + ""); // 0 个人 1企业 2 团队
        switch (modeltype) {
            case QIYEXIANGCE: //宣传相册
                map.put("limit", "20");
                map.put("type", uploadType);
                requestAlbumData(map);
                break;
            case QIYEXINXI: //信息简介
                break;
            case QIYEZIZHI: //专项资质
                getlistByCompany(map);
                break;
            case YEJIZHENGMING: //经营业绩
                performanceCertificateAdminList(map);
                break;
            case QIYEDONGTAI: //经营动态
                getCompanyNewsAdminList(map);
                break;
            case ZHISHICHANQUAN: //知识产权
                //产权类型
                map.put("typesOfPropertyRights", typesOfPropertyRights);
                getListByCompany(map);
                break;
            case HANGYERONGYU: //荣誉荣耀
                getGloryHonorAdminList(map);
                break;
        }
    }

    /**
     * 荣誉荣耀
     *
     * @param map
     */
    private void getGloryHonorAdminList(Map<String, String> map) {
        APIManager.getInstance().getWebsiteInfoAPI().getGloryHonorAdminList(UrlConfig.NEW_BASE_URL+"v1/app/site/GloryHonorAdmin/list",map).enqueue(new ICallBack<BaseEntity<ListResponse<List<GloryHonorAdminEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<GloryHonorAdminEntity>>> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    totalPage = data.getData().getTotal();
                    List<Object> objectList = new ArrayList<>();
                    objectList.addAll(data.getData().getList());
                    listMutableLiveData.postValue(objectList);
                }
            }
        });
    }

    /**
     * 荣誉荣耀列表 单个删除
     */
    private void getGloryHonorAdminBatchDel(Context mContext, String id) {
        APIManager.getInstance().getWebsiteInfoAPI().getGloryHonorAdminBatchDel(id).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    MToast.showToast(mContext, "删除成功");
                    initData(false);
                }
            }
        });
    }

    /**
     * 经营动态列表
     *
     * @param map
     */
    private void getCompanyNewsAdminList(Map<String, String> map) {
        APIManager.getInstance().getWebsiteInfoAPI().getCompanyNewsAdminList(UrlConfig.NEW_BASE_URL+"v1/app/site/CompanyNewsAdmin/list",map).enqueue(new ICallBack<BaseEntity<ListResponse<List<CompanyTradesListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<CompanyTradesListEntity>>> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    totalPage = data.getData().getTotal();
                    List<Object> objectList = new ArrayList<>();
                    objectList.addAll(data.getData().getList());
                    listMutableLiveData.postValue(objectList);
                }
            }
        });
    }

    /**
     * 经营动态列表 单个删除
     */
    public void getCompanyNewsAdminBatchDel(Context mContext, String id) {
        String[] strings = new String[]{id};
        APIManager.getInstance().getWebsiteInfoAPI().getCompanyNewsAdminBatchDel(strings).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    MToast.showToast(mContext, "删除成功");
                    initData(false);
                }
            }
        });
    }

    /**
     * 专项资质 资质列表
     */
    public void getlistByCompany(Map<String, String> map) {
        APIManager.getInstance().getWebsiteInfoAPI().getlistByCompany(UrlConfig.NEW_BASE_URL+"v1/app/site/admin/companyInfoQualification/listByCompany",map).enqueue(new ICallBack<BaseEntity<ListResponse<List<UpdataSpecialQualificationEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<UpdataSpecialQualificationEntity>>> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    totalPage = data.getData().getTotal();
                    List<Object> objectList = new ArrayList<>();
                    objectList.addAll(data.getData().getList());
                    listMutableLiveData.postValue(objectList);
                }
            }
        });
    }

    /**
     * 专项资质列表 单个删除
     */
    public void getCompanyInfoQualificationDelete(Context mContext, String id) {
        APIManager.getInstance().getWebsiteInfoAPI().getCompanyInfoQualificationDelete(id).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    MToast.showToast(mContext, "删除成功");
                    initData(false);
                }
            }
        });
    }

    /**
     * 经营业绩列表
     */
    public void performanceCertificateAdminList(Map<String, String> map) {
        APIManager.getInstance().getWebsiteInfoAPI().performanceCertificateAdminList(WebsiteInfoAPI.WebsiteUrl.URL_SITE_PERFORMANCE_CERTIFICATE,map).enqueue(new ICallBack<BaseEntity<ListResponse<List<OperatingResultsEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<OperatingResultsEntity>>> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    totalPage = data.getData().getTotal();
                    List<Object> objectList = new ArrayList<>();
                    objectList.addAll(data.getData().getList());
                    listMutableLiveData.postValue(objectList);
                }
            }
        });
    }

    /**
     * 经营业绩列表 批量删除
     */
    public void getperformanceCertificateAdminBatchDel(Context mContext, String id) {
        String[] strings = new String[]{id};
        APIManager.getInstance().getWebsiteInfoAPI().getperformanceCertificateAdminBatchDel(strings).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    MToast.showToast(mContext, "删除成功");
                    initData(false);
                }
            }
        });
    }

    /**
     * 知识产权列表
     */
    public void getListByCompany(Map<String, String> map) {
        APIManager.getInstance().getWebsiteInfoAPI().getListByCompany(UrlConfig.NEW_BASE_URL+"v1/app/site/admin/intellectualPropertyRight/listByCompany",map).enqueue(new ICallBack<BaseEntity<ListResponse<List<IPDetailEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<IPDetailEntity>>> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    totalPage = data.getData().getTotal();
                    List<Object> objectList = new ArrayList<>();
                    objectList.addAll(data.getData().getList());
                    listMutableLiveData.postValue(objectList);
                }
            }
        });
    }

    /**
     * 知识产权列表 单个删除
     */
    public void intellectualPropertyRightDelete(Context mContext, String id) {
        APIManager.getInstance().getWebsiteInfoAPI().intellectualPropertyRightDelete(id).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    MToast.showToast(mContext, "删除成功");
                    initData(false);
                }
            }
        });
    }

    /**
     * 企业相册 列表
     */
    public void requestAlbumData(Map<String, String> map) {
        APIManager.getInstance().getWebsiteInfoAPI().getListCompanyAlbumCompany(URL_ALL_SITE_ALBUM ,map).enqueue(new ICallBack<BaseEntity<ListResponse<List<PromotionalAlbumEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<PromotionalAlbumEntity>>> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    totalPage = data.getData().getTotal();
                    List<Object> objectList = new ArrayList<>();
                    objectList.addAll(data.getData().getList());
                    listMutableLiveData.postValue(objectList);
                }
            }
        });
    }

    /**
     * 企业相册 删除
     */
    public void deleteCompanyAlbum(Context mContext, String id) {
        APIManager.getInstance().getWebsiteInfoAPI().deleteCompanyAlbum(id).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    MToast.showToast(mContext, "删除成功");
                    initData(false);
                }
            }
        });
    }

    /**
     * 新增宣传相册照片
     */
    public void addOrUpdateCompanyAlbum(Map<String, Object> map) {
        APIManager.getInstance().getWebsiteInfoAPI().addOrUpdateCompanyAlbum(WebsiteInfoAPI.WebsiteUrl.URL_ADD_UPDATE_COMPANY_ALBUM, map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    initData(false);
                }
            }
        });
    }

    public void uploadAvatar(Context mContext, File file,int siteType) {
        DialogHelper.showProgressDialog(mContext, null, "图片上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        //创建map集合
        Map<String, RequestBody> photos = new HashMap<>();
        //将文件转换成多媒体文件，方便上传
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + RegexUtils.getReplaceAll(file.getName(), "[\u4e00-\u9fa5]", "") + "image.jpg\"", requestBody);
        //接口请求
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data == null || data.getData() == null) {
                    MToast.showToast(mContext, "上传失败");
                    return;
                }
                if (!TextUtils.isEmpty(data.getData().toString())) {
                    Map<String, Object> map = new HashMap();
                    map.put("urls", data.getData().toString());
                    map.put("siteType", siteType + "");
                    // 调用绑定图片路径和企业，然后刷新列表
                    addOrUpdateCompanyAlbum(map);
                }
            }
        });
    }

    /**
     * 相册预览
     **/
    public void openPhotoView(Context mContext, int position, List<Object> objectList) {
        if (objectList.size() > 0) {
            PromotionalAlbumEntity entity = (PromotionalAlbumEntity) objectList.get(position);
            PhotoViewActivity2.launch(mContext, entity.getUrl(), 1, entity.getRemark(), entity.getName());
        } else {
            return;
        }
    }


    /**
     * 视频播放
     **/
    public void openVideoPlayView(Context mContext,PromotionalAlbumEntity entity) {
        APIManager.getInstance().changeAPIManager(UrlConfig.NEW_BASE_URL);
        APIManager.getInstance().getUploadAPI().getVideoUrlById(entity.getUrl()).enqueue(new ICallBack<BaseEntity<AliVideoBean>>() {
            @Override
            public void onSuccess(BaseEntity<AliVideoBean> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    List<VideoBean> videoBeanList = new ArrayList<>();
                    VideoBean videoBean = new VideoBean();
                    videoBean.setVideoId(entity.getUrl());
                    if (data.getData() != null && data.getData().getPlayInfoList() != null ) {
                        if (!data.getData().getPlayInfoList().isEmpty()) {
                            videoBean.setCoverURL(data.getData().getPlayInfoList().get(data.getData().getPlayInfoList().size() - 1).getPlayURL());
                        }
                    }
                    videoBean.setCover(data.getData().getVideoBase().getCoverURL());
                    videoBeanList.add(videoBean);
                    PhotoViewActivity2.launch(mContext, videoBeanList, 2, entity.getRemark(), entity.getName());
                } else {
                    MToast.showToast(mContext, data.getMsg());
                }
            }
        });
        APIManager.getInstance().changeAPIManager(UrlConfig.BASE_URL);
    }


    /**
     * 列表详情触发
     *
     * @param mContext
     * @param id
     */
    public void onRoomClick(Context mContext, String id, String name) {
        String param = "";
        switch (modeltype) {
            case QIYEXIANGCE: //宣传相册
                param = "";
                break;
            case QIYEXINXI: //信息简介
                break;
            case QIYEZIZHI: //专项资质
                if (siteType == 0){
                    param = "personalSpecialinfo";
                } else if (siteType == 1) {
                    param = "specialinfo";
                } else if (siteType == 2) {
                    param = "teamSpecialinfo";
                } else if (siteType == 3){
                    param = "organspecialinfo";
                }
                break;
            case YEJIZHENGMING: //经营业绩
                if (siteType == 0){
                    param = "PersonManageDetail";
                } else if (siteType == 1) {
                    param = "EPmanageDetail";
                } else if (siteType == 2){
                    param = "teamManageDetail";
                } else if (siteType == 3){
                    param = "organPersonManageDetail";
                }
                break;
            case QIYEDONGTAI: //经营动态
                if (siteType == 0){
                    param = "PersonDynamicDetail";
                } else if (siteType == 1){
                    param = "EPdynamicDetail";
                } else if (siteType == 2){
                    param = "teamDynamicDetail";
                } else if (siteType == 3){
                    param = "organPersonDynamicDetail";
                }
                break;
            case ZHISHICHANQUAN: //知识产权
                if (siteType == 0){
                    if ("商标".equals(name)) {
                        param = "personalTrademarkinfo";
                    } else if ("专利".equals(name)) {
                        param = "personalPatentinfo";
                    } else if ("版权".equals(name)) {
                        param = "personalCopyrightinfo";
                    }
                } else if (siteType == 1) {
                    if ("商标".equals(name)) {
                        param = "trademarkinfo";
                    } else if ("专利".equals(name)) {
                        param = "patentinfo";
                    } else if ("版权".equals(name)) {
                        param = "copyrightinfo";
                    }
                } else if (siteType == 2){
                    if ("商标".equals(name)) {
                        param = "teamTrademarkinfo";
                    } else if ("专利".equals(name)) {
                        param = "teamPatentinfo";
                    } else if ("版权".equals(name)) {
                        param = "teamCopyrightinfo";
                    }
                } else if (siteType == 3){
                    if ("商标".equals(name)) {
                        param = "organtrademarkinfo";
                    } else if ("专利".equals(name)) {
                        param = "organpatentinfo";
                    } else if ("版权".equals(name)) {
                        param = "organcopyrightinfo";
                    }
                }
                break;
            case HANGYERONGYU: //荣誉荣耀
                if (siteType == 0) {
                    param = "PersonHonorDetail";
                } else if (siteType == 1) {
                    param = "honorDetail";
                } else if (siteType == 2) {
                    param = "teamHonorDetail";
                } else if (siteType == 3) {
                    param = "organPersonHonorDetail";
                }
                break;
        }
        if (TextUtils.isEmpty(param)) MToast.showToast(mContext, "请检查接口路由");
        getH5Url(mContext, id, param);
    }

    private void getH5Url(Context mContext, String id, String param) {
        DialogHelper.showProgressDialog(mContext, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(param).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl();
                    url = url + "?id=" + id;
                    WebViewX5HostActivity.start(mContext, url);
                } else {
                    MToast.showToast(mContext, data.getMsg());
                }
            }
        });
    }

    /**
     * 列表删除按钮触发
     *
     * @param mContext
     * @param id
     */
    public void onDel(Context mContext, String id) {
        switch (modeltype) {
            case QIYEXIANGCE: //宣传相册
                deleteCompanyAlbum(mContext, id);
                break;
            case QIYEXINXI: //信息简介
                break;
            case QIYEZIZHI: //专项资质
                getCompanyInfoQualificationDelete(mContext, id);
                break;
            case YEJIZHENGMING: //经营业绩
                getperformanceCertificateAdminBatchDel(mContext, id);
                break;
            case QIYEDONGTAI: //经营动态
                getCompanyNewsAdminBatchDel(mContext, id);
                break;
            case ZHISHICHANQUAN: //知识产权
                intellectualPropertyRightDelete(mContext, id);
                break;
            case HANGYERONGYU: //荣誉荣耀
                getGloryHonorAdminBatchDel(mContext, id);
                break;
        }
    }

    /**
     * 列表编辑按钮触发
     *
     * @param mContext
     * @param id
     * @param name
     */
    public void onEditor(Context mContext, String id, String name) {
        switch (modeltype) {
            case QIYEXIANGCE: //宣传相册
                break;
            case QIYEXINXI: //信息简介
                break;
            case QIYEZIZHI: //专项资质
                WebsiteUpDataZhuanXiangZiZhiActivity.start(mContext, name, id,siteType);
                break;
            case YEJIZHENGMING: //经营业绩
                WebsiteUpDataJingYingYeJiActivity.start(mContext, id,siteType);
                break;
            case QIYEDONGTAI: //经营动态
                WebsiteUpDataJYDTActivity.start(mContext, name, id,siteType);
                break;
            case ZHISHICHANQUAN: //知识产权
                WebsiteUpDataZhiShiChanQuanActivity.start(mContext, name, id,siteType);
                break;
            case HANGYERONGYU: //荣誉荣耀
                WebsiteUpDataRongYuRongYaoActivity.start(mContext, name, id,siteType);
                break;
        }
    }
}
